﻿@page "/announcement/edit"
@layout	ManagerLayout
@attribute [Authorize(Roles ="教师，管理员")]

@inject IAnnouncementService AnnouncementService
@inject IMessageService MessageService
@inject NavigationManager NavigationManager

@implements IDisposable
@inject ILocalStorageService LocalStorageService

@using Blazored.TextEditor

<Form Model="@_addAnnouncement"
              LabelColSpan="8"
              WrapperColSpan="16"
              OnFinish="OnFinish"
              Size="Default">
              <FormItem Label="公告标题">
                  <Input @bind-Value="@context.Title"/>
              </FormItem>
              <FormItem Label="公告子标题">
                   <Input @bind-Value="@context.SubTitle" />
              </FormItem>
              <FormItem Label="公告标签(可选)">
                <RadioGroup @bind-Value="@context.Icon">
                    @foreach (var iconName in _iconList)
                    {
                        <Radio Value="@iconName">
                            <Icon Type="@iconName" Theme="outline"/>
                        </Radio>
                    }
                </RadioGroup>
              </FormItem>
    <BlazoredTextEditor @ref="@_quillHtml" Placeholder="公告正文">
        <ToolbarContent>
            <select class="ql-header">
                <option selected=""></option>
                <option value="1"></option>
                <option value="2"></option>
                <option value="3"></option>
                <option value="4"></option>
                <option value="5"></option>
            </select>
            <span class="ql-formats">
                <button class="ql-bold"></button>
                <button class="ql-italic"></button>
                <button class="ql-underline"></button>
                <button class="ql-strike"></button>
            </span>
            <span class="ql-formats">
                <select class="ql-color"></select>
                <select class="ql-background"></select>
            </span>
            <span class="ql-formats">
                <button class="ql-list" value="ordered"></button>
                <button class="ql-list" value="bullet"></button>
            </span>
            <span class="ql-formats">
                <button class="ql-link"></button>
            </span>
            <span class="ql-formats">
                <button class="ql-script" value="sub"></button>
                <button class="ql-align" value="center"></button>
                <button class="ql-align" value="right"></button>

                <button class="ql-code-block"></button>
                <button class="ql-indent" value="+1"></button>
            </span>
        </ToolbarContent>
        </BlazoredTextEditor>
        <FormItem>
        <Button Type="primary" HtmlType="submit" Style="margin-top:16px">
            提交
        </Button>
        </FormItem>
</Form>



@code {
    private AddAnnouncement _addAnnouncement = new();

    private BlazoredTextEditor _quillHtml;
    [CascadingParameter]
    private Task<AuthenticationState>? _authenticationState { get; set; }
    private Guid userId;
    private string _message = string.Empty;
    private List<string> _iconList = new() { "stop", "warning", "question-circle","carry-out","bug" };

    protected override async void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            await LoadCache();
            registration =
                NavigationManager.RegisterLocationChangingHandler(OnLocationChanging);
        }
        base.OnAfterRender(firstRender);
    }

    private async void OnFinish(EditContext editContext)
    {  
        var state = await _authenticationState;
        var idstr = state.User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (idstr != null)
        {
            userId = Guid.Parse(idstr);
            _addAnnouncement.UserId = userId;
            _addAnnouncement.HtmlText =await _quillHtml.GetHTML();

            var response=   await AnnouncementService.AddAsync(_addAnnouncement);
            if (response.Success)
            {
                await ClearCache();
                MessageService.Success("成功发布公告!");
                NavigationManager.NavigateTo("/");
            }
            else
            {
                MessageService.Error(response.Message);
            }
        }       
    }

    private IDisposable? registration;

    private async ValueTask OnLocationChanging(LocationChangingContext context)
    {
        await WriteCache();       
        // context.PreventNavigation();
    }

    private const string CACHEKEY = "AnnouncementCache";
    async Task LoadCache()
    {
        string cache = await LocalStorageService.GetItemAsStringAsync(CACHEKEY);
        if (!string.IsNullOrEmpty(cache))
        {
            await _quillHtml.LoadHTMLContent(cache);
            MessageService.Info("已加载上一次的编辑内容");
        }
    }

    async Task WriteCache()
    {
        string cache = await _quillHtml.GetHTML();
        if (!string.IsNullOrEmpty(cache))
        {
            await LocalStorageService.SetItemAsStringAsync(CACHEKEY, cache);
            MessageService.Info("编辑内容尚未提交，已保存");
        }       
    }

    async Task ClearCache()
    {
        await LocalStorageService.RemoveItemAsync(CACHEKEY);
    }

    public void Dispose() => registration?.Dispose();
}
